﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace ClientRegister
{
    public class GetNextID
    {
        ConnectDB con = new ConnectDB();
        SqlConnection cnn;
        SqlCommand cmd;
        SqlDataReader sdr;

        //Moi Client prefixID se khac nhau
        public string prefixID = "A";

        public string EmpTB = "Employees";
        public string studentTB = "Students";
        public string classTB = "Classes";
        public string CourseTB = "Courses";
        public string TeacherTB = "Teachers";
        public string SubjectTB = "Subjects";
        public string IDCol = "ID";

        public string getLastID(string tableName, string column)
        {
            string result = "";
            string query = string.Format("SELECT MAX(RIGHT({1},4)) FROM {0}",tableName, column);
            //ORDER BY {1} DESC
            cnn = con.Connect();
            cnn.Open();
            cmd = new SqlCommand(query, cnn);
            sdr = cmd.ExecuteReader();
            if (sdr.Read())
            {
                result = sdr.GetValue(0).ToString();
            }
            return prefixID + result;
            
        }

        public string NextID(string lastID, string prefixID)
        {
            if (lastID == "")
            {
                return prefixID + "0001";  // fixwidth default
            }
            int nextID = int.Parse(lastID.Remove(0, prefixID.Length)) + 1;
            int lengthNumerID = lastID.Length - prefixID.Length;
            string zeroNumber = "";
            for (int i = 1; i <= lengthNumerID; i++)
            {
                if (nextID < Math.Pow(10, i))
                {
                    for (int j = 1; j <= lengthNumerID - i; i++)
                    {
                        zeroNumber += "0";
                    }
                    return prefixID + zeroNumber + nextID.ToString();
                }
            }
            return prefixID + nextID;
        }
    }
}
